package com.kingdee.jdy.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.jdy.util.HttpUtil;
import java.util.HashMap;
import java.util.Random;
/**
 * 客户
 */
public class CustomerController {

    public static long saveCustomer(HashMap<String, Object> urlParam, HashMap<String, Object> headerParam)
        throws Exception {

        long customerid_id = 0;
        JSONObject jsonCustomer = prepareCustomerParam();
        JSONObject resCustomer = HttpUtil
            .doPost("http://api.kingdee.com/jdy/basedata/customer_save", urlParam, headerParam, jsonCustomer.toJSONString());

        if (resCustomer != null) {
            JSONObject data = resCustomer.getJSONObject("data");
            if (data != null) {
                String success = data.getString("success");
                if (success.equalsIgnoreCase("true")) {
                    customerid_id = data.getJSONArray("successPkIds").getLongValue(0);
                    System.out.println("同步客户成功！customerid_id=" + customerid_id);
                } else {
                    System.out.println("同步客户失败！");
                }
            } else {
                System.out.println("同步客户失败！");
            }
        } else {
            System.out.println("同步客户失败！");
        }
        return customerid_id;
    }

    public static long getAnyOneCustomer(HashMap<String, Object> urlParam, HashMap<String, Object> headerParam)
        throws Exception {

        long customerid_id = 0;
        JSONObject resCustomer = HttpUtil
            .doPost("http://api.kingdee.com/jdy/basedata/customer_list", urlParam, headerParam, null);

        if (resCustomer != null) {
            JSONObject data = resCustomer.getJSONObject("data");
            if (data != null) {
                int curpagesize = data.getIntValue("curpagesize");
                if (curpagesize > 0) {
                    customerid_id = data.getJSONArray("rows").getJSONObject(0).getLongValue("id");
                }
            } else {
                System.out.println("查询客户失败！");
            }
        } else {
            System.out.println("查询客户失败！");
        }
        return customerid_id;
    }

    public static JSONObject prepareCustomerParam() throws Exception{

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", null);
        jsonObject.put("name", "demo测试商品" + new Random().nextInt());
        jsonObject.put("number", "demoCutomer" + new Random().nextInt());

        JSONArray contactpersonsArray = new JSONArray();
        JSONObject entity = new JSONObject();
        entity.put("id", null);
        entity.put("contactperson", "马云云");
        entity.put("mobile","123456789");
        contactpersonsArray.add(entity);

        jsonObject.put("contactpersons", contactpersonsArray);

        return jsonObject;
    }
}
